package com.cskaoyan.controller;

import com.cskaoyan.vo.BaseRespVo;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * RESTful风格注解
 * @author stone
 * @date 2022/10/07 16:07
 */
@RestController
public class RestfulController {

    //@RequestMapping("*/article/details/*")
    //public BaseRespVo articleDetails(HttpServletRequest request) {
    //    String requestURI = request.getRequestURI();
    //    // 解析字符串获得第一个/之前和最后一个/之后的字符串作为name和id
    //    return BaseRespVo.ok();
    //}
    // jdbc : select id,username,password from cskaoyan_user where username = ? and password= ?

    // 通过{}指定占位符的名称
    @RequestMapping("{username}/article/details/{id}")
    public BaseRespVo articleDetails(@PathVariable("username") String username,
                                     @PathVariable("id") Integer id) {

        return BaseRespVo.ok("username = " + username + ";id=" + id);
    }

    // localhost:8080/rest/login?username=songge&password=niupi
    // 使用注解后，必须要携带username和password的信息
    @RequestMapping("rest/login")
    public BaseRespVo login(@RequestParam("username") String usernamex,
                            @RequestParam("password") String passwordy) {
        return BaseRespVo.ok();
    }

    // 可以String 或 String[] 来接收
    // 如果里面使用到逗号，就可以使用数组来接收 → String.split(",")
    @RequestMapping("header")
    public BaseRespVo header(@RequestHeader("Accept") String[] accept,
                             @RequestHeader("Host")String host) {
        return BaseRespVo.ok();
    }

    //获得cookie中songge这个name对应的value
    @RequestMapping("cookie/value1")
    public BaseRespVo cookieValue1(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("songge".equals(cookie.getName())) {
                String value = cookie.getValue();
                return BaseRespVo.ok(value);
            }
        }
        return BaseRespVo.ok();
    }
    @RequestMapping("cookie/value2")
    public BaseRespVo cookieValue2(@CookieValue("songge") String value) {

        return BaseRespVo.ok(value);
    }

    // localhost:8080/session1?username=xxx可以向session中放入数据
    // OtherParameterController中的handler方法
    @RequestMapping("session/attribute1")
    public BaseRespVo sessionAttribute1(HttpSession session) {
        String username = (String) session.getAttribute("username");
        return BaseRespVo.ok(username);
    }
    // 形参的类型是Object，放入的时候是什么类型的值，就可以直接使用什么类型的值来接收
    @RequestMapping("session/attribute2")
    public BaseRespVo sessionAttribute2(@SessionAttribute("username") String username) {
        return BaseRespVo.ok(username);
    }
}
